/**
 * Copyright (C) 2011 Taobao Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taobao.jaket;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taobao.jaket.adapter.TypeAdapter;
import com.taobao.jaket.model.MethodDefinition;
import com.taobao.jaket.model.ServiceDefinition;
import com.taobao.jaket.model.SignatureDefinition;
import com.taobao.jaket.model.TypeDefinition;
import com.taobao.jaket.util.TypeUtil;

/**
 * A helper class for generating the service description model
 * 
 * @author Xueqiang Mi
 */
public class Builder extends BuilderSupport {

    public static ServiceDefinition buildJavaSchema(final Class<?> serviceType) {
        return build(serviceType, "java");
    }

    public static ServiceDefinition buildJsonSchema(final Class<?> serviceType) {
        return build(serviceType, "json");
    }

    public static TypeDefinition toJavaType(final Type type) {
        Map<Type, TypeDefinition> typeCache = new HashMap<Type, TypeDefinition>();
        return toJavaType(type, typeCache);
    }

    public static TypeDefinition toJsonType(final Type type) {
        Map<Type, TypeDefinition> typeCache = new HashMap<Type, TypeDefinition>();
        return toJsonType(type, typeCache);
    }

    private static ServiceDefinition build(final Class<?> serviceType, String schemeType) {
        ServiceDefinition sd = new ServiceDefinition();
        SignatureDefinition signature = sd.getSignature();
        signature.setCanonicalName(serviceType.getCanonicalName());

        List<Method> methods = TypeUtil.getMethods(serviceType);
        for (Method method : methods) {
            MethodDefinition md = new MethodDefinition();
            md.setName(method.getName());
            md.setArgSigs(createParamSignature(method.getParameterTypes()));

            Type[] paramTypes = method.getGenericParameterTypes();
            for (Type t : paramTypes) {
                TypeDefinition td = null;
                if ("json".equals(schemeType)) {
                    td = toJsonType(t);
                } else {
                    td = toJavaType(t);
                }
                md.getParameters().add(td);
            }
            Type t = method.getGenericReturnType();
            TypeDefinition td = null;
            if ("json".equals(schemeType)) {
                td = toJsonType(t);
            } else {
                td = toJavaType(t);
            }
            md.setReturnType(td);
            sd.getMethods().add(md);
        }
        return sd;
    }

    private static String[] createParamSignature(Class<?>[] args) {
        if (args == null || args.length == 0) {
            return new String[] {};
        }
        String[] paramSig = new String[args.length];
        for (int i = 0; i < args.length; i++) {
            paramSig[i] = args[i].getName();
        }
        return paramSig;
    }

    private static TypeDefinition toJavaType(final Type type, Map<Type, TypeDefinition> typeCache) {
        TypeAdapter typeAdapter = getTypeAdapter(type);
        if (typeAdapter != null) {
            return typeAdapter.toJavaType(type);
        }

        Class<?> clazz = (Class<?>) type;
        // try to get result from cache
        if (typeCache.containsKey(type)) {
            return typeCache.get(type);
        } else {
            TypeDefinition ref = new TypeDefinition();
            ref.set$ref(clazz.getCanonicalName());
            typeCache.put(type, ref);
        }

        // process custom object type and store it into cache
        TypeDefinition td = new TypeDefinition();
        td.setId(clazz.getCanonicalName());
        td.setType(clazz.getCanonicalName());
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            String name = field.getName();
            Class<?> c = field.getType();

            TypeDefinition fieldTd = null;
            if (typeCache.containsKey(c)) {
                fieldTd = typeCache.get(c);
            } else {
                fieldTd = toJavaType(c);
            }
            td.getProperties().put(name, fieldTd);
        }
        return td;
    }

    private static TypeDefinition toJsonType(final Type type, Map<Type, TypeDefinition> typeCache) {
        TypeAdapter typeAdapter = getTypeAdapter(type);
        if (typeAdapter != null) {
            return typeAdapter.toJsonType(type);
        }

        Class<?> clazz = (Class<?>) type;
        // try to get result from cache
        if (typeCache.containsKey(type)) {
            return typeCache.get(type);
        } else {
            TypeDefinition ref = new TypeDefinition();
            ref.set$ref(clazz.getCanonicalName());
            typeCache.put(type, ref);
        }

        // process custom object type and store it into cache
        TypeDefinition td = new TypeDefinition();
        td.setId(clazz.getCanonicalName());
        td.setType(clazz.getCanonicalName());
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            String name = field.getName();
            Class<?> c = field.getType();

            TypeDefinition fieldTd = null;
            if (typeCache.containsKey(c)) {
                fieldTd = typeCache.get(c);
            } else {
                fieldTd = toJsonType(c);
            }
            td.getProperties().put(name, fieldTd);
        }
        return td;
    }
}
